﻿Imports SISSAT.BusinessLayer.Services
Imports SISSAT.Administration.DomainModels
Imports SISSAT.Administration.Services
Imports SISSAT.BusinessLayer.DomainModels

Namespace Views
    Public Class WebUserDetailControlPresenter

        Private Property View As IWebUserDetailControlView
        Private Property EmployeeService As IEmployeeService
        Private Property Service As IUserService

        Public Sub New(view As IWebUserDetailControlView)
            Service = New UserService
            EmployeeService = New EmployeeService
            Me.View = view
            AddHandler Me.View.OnClear, AddressOf OnClear
            AddHandler Me.View.OnInitialization, AddressOf OnInitialization
            AddHandler Me.View.OnSubmit, AddressOf OnSubmit
            AddHandler Me.View.OnUpdate, AddressOf OnUpdate
        End Sub

        Private Sub OnInitialization()
            If String.Compare(Me.View.EmployeeCode, "new", True) = 0 Then
                Return
            End If

            Dim entity As SouthdaleUser = Service.ReadByEmployeeCode(Me.View.EmployeeCode)

            If entity Is Nothing Then
                Throw New NullReferenceException()
            End If

            Me.View.OldPassword = entity.Password
            Me.View.Username = entity.Username
        End Sub

        Private Sub OnClear()
            Me.View.OldPassword = String.Empty
            Me.View.NewPassword = String.Empty
            Me.View.Username = String.Empty

            OnInitialization()
        End Sub

        Private Sub OnSubmit()
            Dim employeeId As Integer = Me.View.EmployeeId
            If employeeId = 0 Then
                Dim employee As Employee = EmployeeService.ReadByCode(Me.View.EmployeeCode)
                If employee Is Nothing Then
                    Throw New NullReferenceException()
                End If

                employeeId = employee.EmployeeId
            End If

            Service.Create(employeeId, Me.View.Username, Me.View.OldPassword, Me.View.CurrentUserId)
        End Sub

        Private Sub OnUpdate()
            If String.IsNullOrEmpty(Me.View.EmployeeCode) Then
                Throw New NoNullAllowedException()
            End If

            Dim entity As SouthdaleUser = Service.AuthenticateUser(Me.View.Username, Me.View.OldPassword)
            If entity Is Nothing Then
                OnClear()
                Throw New ArgumentNullException("Password is incorrect.")
            End If

            entity = Service.ReadByEmployeeCode(Me.View.EmployeeCode)
            entity.Password = Me.View.NewPassword
            entity.Username = Me.View.Username

            Service.Edit(entity, Me.View.CurrentUserId)
        End Sub

    End Class
End Namespace

